<?php
include "otamu_config.php";
$layout = "layout";
define("_VIEWPATH_","views/ref/");
class RefObject extends ADOdb_Active_Record {}

if (!isset($_GET['act'])) $_GET['act'] = ''; 
$the_table = $_REQUEST['table'];
$ref = new RefObject($_REQUEST['table']);
//print_r($ref);
$fields = $ref->getAttributeNames();
//print_r($_REQUEST);
$pkeys  = $ref->getPrimaryKeys($DB,$the_table);

switch ($_GET['act']) {
	case "all_data" :
		$ref_tables = array('bangsa','cawangan','jantina','jawatan','negeri','status_keahlian');
		break;

	case "new" :
		$the_pkey_value = $_REQUEST[$pkeys[0]];		
		$object = new RefObject($_REQUEST['table']);
		break;

	case "create" :
		$the_pkey_value = $_REQUEST[$pkeys[0]];
		
		$object = new RefObject($_REQUEST['table']);
		
		foreach ($fields as $field) {
			if (in_array($field,$pkeys)) { 1; }
			else { $object->$field = $_REQUEST[$field];}
		}

		if (!$object->save()) { 
			$_SESSION['error'] = $object->ErrorMsg();
			$act = $_GET['act'] = "new";break;
		}else {
			$_SESSION['flash'] = ucwords(ereg_replace("_"," ",$the_table)) . ' has been added';
		}
		header("Location: ref.php?act=list&table=$the_table");
		break;
		
	case "edit" :
		$hasPkey = false;
		foreach ($pkeys as $pkey) {
			if (isset($_REQUEST["$pkey"])) $hasPkey = true; 
		}
		if (!$hasPkey) exitError('No Primary Key Input');
		
		$the_pkey_value = $_REQUEST[$pkeys[0]];
		
		$object = new RefObject($_REQUEST['table']);
		$object->Load("$pkeys[0]='$the_pkey_value'");
		break;

	case "update" :
		$hasPkey = false;
		foreach ($pkeys as $pkey) {
			if (isset($_REQUEST["$pkey"])) $hasPkey = true; 
		}
		if (!$hasPkey) exitError('No Primary Key Input');
		
		$the_pkey_value = $_REQUEST[$pkeys[0]];
		
		$object = new RefObject($_REQUEST['table']);
		$object->Load("$pkeys[0]='$the_pkey_value'");
		
		foreach ($fields as $field) {
			if (in_array($field,$pkeys)) { 1; }
			else { $object->$field = $_REQUEST[$field];}
		}

		if (!$object->save()) { 
			$_SESSION['error'] = $object->ErrorMsg();
		}else {
			$_SESSION['flash'] = ucwords(ereg_replace("_"," ",$the_table)) . ' has been updated';
		}
		header("Location: ref.php?act=list&table=$the_table");
		
		break;

	case "delete" :
		$hasPkey = false;
		foreach ($pkeys as $pkey) {
			if (isset($_REQUEST["$pkey"])) $hasPkey = true; 
		}
		if (!$hasPkey) exitError('No Primary Key Input');
		
		$the_pkey_value = $_REQUEST[$pkeys[0]];
		
		$object = new RefObject($_REQUEST['table']);
		$object->Load("$pkeys[0]='$the_pkey_value'");
		if (!$object->delete()) { 
			$_SESSION['flash'] = $object->ErrorMsg();
		}else {
			$_SESSION['flash'] = ucwords(ereg_replace("_"," ",$the_table)) . ' has been deleted';
		}
		header("Location: ref.php?act=list&table=$the_table");
				
		break;
	
	default :
		$act = "list";
		$sql = "SELECT * FROM $the_table";
		$res = $DB->Execute($sql);
		break;
}

include _VIEWPATH_."$layout.php";
?>
